//
//  xsBossIPBackgroundTableView.m
//  digital_robot_demo
//
//  Created by xskj on 2024/9/2.
//

#import "xsBossIPBackgroundTableView.h"
#define XSWeakSelf   __weak typeof(self) weakSelf = self;
#define ScreenW UIScreen.mainScreen.bounds.size.width
#define ScreenH UIScreen.mainScreen.bounds.size.height


@interface xsBossIPBackgroundTableView()<UITableViewDelegate,UITableViewDataSource>


@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) UIView *tableEmptyView;
@property (nonatomic,weak) UIImageView * tableEmptyImage;
@property (nonatomic,weak) UILabel * tableEmptyLabel;
@property (nonatomic,weak) UIButton *covertableEmptyViewButton;

@property (nonatomic,assign)BOOL isMeModel;// NO不是  YES是


@property (nonatomic,copy)NSString *keywordString;
@property (nonatomic,assign) NSInteger tagId;


@property (nonatomic,assign)NSInteger page;

@end

@implementation xsBossIPBackgroundTableView



- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style withIsMe:(BOOL)isMe{
    
    self = [super initWithFrame:frame style:style];
    if(self){
        //        self = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
      
        self.isMeModel  = isMe;
        //[self.dataArray addObjectsFromArray:dArray];
        self.delegate = self;
        self.dataSource = self;
        //        self.rowHeight = 50;
        self.showsVerticalScrollIndicator = NO;
        
        self.page = 1;
        
        //        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 0.1)];
        //        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 0.1)];
        self.backgroundColor = UIColor.clearColor;
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.separatorColor = UIColor.clearColor;
        
        //    @"empty"
        //            self.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"empty"
        //             titleStr:@"暂无溯源文件"
        //            detailStr:@""];
        [self addSubview:self.tableEmptyView];
        [self.tableEmptyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
            //            make.size.mas_equalTo(CGSizeMake(90, 90+5+21));
            make.size.mas_equalTo(CGSizeMake(250, 250));
        }];
        //        NSLog(@"XSHeJiaoEditWordTableView.frame==%@\n",NSStringFromCGRect(self.frame));
        
//        [self.tableEmptyImage mas_remakeConstraints:^(MASConstraintMaker *make) {
//            make.centerX.equalTo(_tableEmptyView);
//            make.centerY.equalTo(_tableEmptyView.mas_centerY).offset(-10);
//            make.size.mas_equalTo(CGSizeMake(80.55, 86.58));
//        }];
//        [self.tableEmptyLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
//            make.centerX.equalTo(_tableEmptyView);
//            make.top.equalTo(self.tableEmptyImage.mas_bottom).offset(5);
//        }];
//        self.tableEmptyImage.backgroundColor = kRandomColor;
//        self.tableEmptyLabel.backgroundColor = kRandomColor;
//
//
//        self.covertableEmptyViewButton.frame = CGRectMake(0, 0, self.width, self.height);
        
        XSWeakSelf;
        self.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
            
            weakSelf.page = 1;
            [weakSelf.dataArray removeAllObjects];
            
            [self getListDataWithTagId:weakSelf.tagId whitKeyWord:weakSelf.keywordString];
            
        }];
//
////        self.mj_footer= [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
////            ++self.page;
////            [self getNumberPeopleDataWithAspectRatio:aspectRatio withCategoryId:categoryId];
////        }];
        
    }
    return self;
}


- (void)arrowButtonAction:(UIButton *)sender{
    NSLog(@"arrowButtonAction\n\n");
//    if(self.downArrowButtonBlock)
//    {
//        self.downArrowButtonBlock();
//    }
}
#pragma mark - UITableViewDeletage
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    NSLog(@"self.dataArray.count==%ld\n",self.dataArray.count);
   
    self.tableEmptyView.hidden = self.dataArray.count;
    return self.dataArray.count;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70.0;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//
//    if(self.tuiJianVCTp==tuiJianVCType_recommendList){
//        return 103.0;
//    }
//    else{
//        return 0;
//    }
//}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    xsBossIPBackgroundTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"xsBossIPBackgroundTableViewCellID"];
    if(!cell){
        cell = [[xsBossIPBackgroundTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"xsBossIPBackgroundTableViewCellID" withIsMe:self.isMeModel];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.isMeModel = self.isMeModel;
    
    if(indexPath.row<self.dataArray.count){
        xsBossIPBackgroundTableViewCellModel *fmodel = self.dataArray[indexPath.row];
        cell.model = fmodel;
        //
        
    }
    XSWeakSelf;
    cell.cellUseButtonCallBackBlock = ^(xsBossIPBackgroundTableViewCellModel * _Nonnull cellmodel) {
        if(weakSelf.tableViewCellDeleteCallBackBlock){
            weakSelf.tableViewCellUseButtonCallBackBlock(cellmodel);
        }
    };
    cell.cellDeleteCallBackBlock = ^(xsBossIPBackgroundTableViewCellModel * _Nonnull cellmodel2) {
        if(weakSelf.tableViewCellDeleteCallBackBlock){
            weakSelf.tableViewCellDeleteCallBackBlock(cellmodel2);
        }
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"didSelectRowAtIndexPath--indexPath.section==%d--indexPath.row==%d",(int)indexPath.section,(int)indexPath.row);
    
    
    
   
    
    if(indexPath.row<self.dataArray.count){
        
        xsBossIPBackgroundTableViewCellModel *model = self.dataArray[indexPath.row];
        
        
        for (xsBossIPBackgroundTableViewCellModel *tempModel in self.dataArray) {
            if(tempModel.Id==model.Id){
                tempModel.isUse = !tempModel.isUse;
                NSLog(@"tempModel.isUse==%d",tempModel.isUse);
            }
            else{
                tempModel.isUse = NO;
                NSLog(@"tempModel.isUse--NO==%d",tempModel.isUse);
            }
        }
        
        
        if(self.tableViewCellBeClickCallBackBlock){
            self.tableViewCellBeClickCallBackBlock(model);
        }
        
        [self reloadData];
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    UIView *hView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 0.01)];
    //    hView.backgroundColor = COLOR_VCViewBgcolor;
    //    [self addHeadSubViews:hView];
    return hView;
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return [UIView new];
}
- (NSMutableArray *)dataArray{
    
    if(!_dataArray){
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (UIView *)tableEmptyView{
    
    if (!_tableEmptyView) {
        _tableEmptyView = [[UIView alloc] init];
        _tableEmptyView.backgroundColor = UIColor.clearColor;
        
        
        UITapGestureRecognizer *tableEmptyViewRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableEmptyImageGestureEvent:)];
        [_tableEmptyView addGestureRecognizer:tableEmptyViewRecognizer];
        
        UIImageView *tableEmptyImage = [[UIImageView alloc] init];
        tableEmptyImage.image = [UIImage imageNamed:@"CYNotSearchResultData"];
        [_tableEmptyView addSubview:tableEmptyImage];
        tableEmptyImage.backgroundColor = UIColor.clearColor;
        self.tableEmptyImage = tableEmptyImage;
        
        UILabel *tableEmptyLabel = [[UILabel alloc] init];
        tableEmptyLabel.text = @"暂无数据";//kLocalizedString(@"暂无数据");
        tableEmptyLabel.font = [UIFont systemFontOfSize:16];//Font(16);
        tableEmptyLabel.numberOfLines = 0;
        tableEmptyLabel.textAlignment = NSTextAlignmentCenter;
        tableEmptyLabel.textColor = COLOR_HEX(0x999999);
        [_tableEmptyView addSubview:tableEmptyLabel];
        self.tableEmptyLabel = tableEmptyLabel;
        
        tableEmptyImage.userInteractionEnabled = YES;
        tableEmptyLabel.userInteractionEnabled = YES;

        UITapGestureRecognizer *tableEmptyImageRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableEmptyImageGestureEvent:)];
        [tableEmptyImage addGestureRecognizer:tableEmptyImageRecognizer];

        UITapGestureRecognizer *tableEmptyLabelRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableEmptyLabelGestureEvent:)];
        [tableEmptyLabel addGestureRecognizer:tableEmptyLabelRecognizer];
        
        [tableEmptyImage mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_tableEmptyView);
            make.centerY.equalTo(_tableEmptyView.mas_centerY).offset(-10);
            make.size.mas_equalTo(CGSizeMake(80.55, 86.58));
        }];
        [tableEmptyLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_tableEmptyView);
            make.top.equalTo(tableEmptyImage.mas_bottom).offset(5);
        }];
        //
        //        UIButton *covertableEmptyViewButton = [UIButton buttonWithType:UIButtonTypeCustom];
        //        covertableEmptyViewButton.backgroundColor = UIColor.purpleColor;//UIColor.clearColor;
        //        [_tableEmptyView addSubview:covertableEmptyViewButton];
        //        self.covertableEmptyViewButton = covertableEmptyViewButton;
        //        XSWeakSelf;
        //        [covertableEmptyViewButton addTapRunWithBlock:^(UIButton * _Nonnull YSBtn) {
        //            if(weakSelf.tableViewNotContentDataBgViewBeClickEvent){
        //                weakSelf.tableViewNotContentDataBgViewBeClickEvent();
        //            }
        //        }];
        
    }
    return _tableEmptyView;
    
}
- (void)tableEmptyImageGestureEvent:(UITapGestureRecognizer *)sender{
    
    [self tableEmptyLabelGestureEvent:sender];
}
- (void)tableEmptyLabelGestureEvent:(UITapGestureRecognizer *)sender{
    
    NSLog(@"tableEmptyLabelGestureEvent");
    
    if(self.dataArray.count<=0){
//        [self getListDataWithTagId:self.tagId whitKeyWord:self.keywordString];
        [self.mj_header beginRefreshing];
    }
}

//- (void)xsChangeData:(NSArray *)xsData{
//    [self.dataArray removeAllObjects];
//    [self.dataArray addObjectsFromArray:xsData];
//    
//}

//keyword    关键词,示例值(抒情的)   false string
//tagId    标签id 不传查询全部,示例值(1)  false integer(int32)
- (void)xsTableDataWithTagId:(NSInteger )tagId whitKeyWord:(NSString *)keywordString{
    
    self.tagId = tagId;
    self.keywordString = keywordString;
    [self.dataArray removeAllObjects];
    self.page = 1;
    
    [self getListDataWithTagId:tagId whitKeyWord:keywordString];
    //[self.mj_header beginRefreshing];
}

- (void)getListDataWithTagId:(NSInteger )tagId whitKeyWord:(NSString *)keywordString{
    //
        
        XSWeakSelf;

                             
//        NSString *tempUrl = @"https://mall219.writemall.com/bossapi/music/list";
    
    NSString *tempUrl = [NSString stringWithFormat:@"%@%@",API_BASEURL_BossIP,@"music/list"];
    
        
//    {
//      "page": 1,
//      "limit": 10,
//      "keyword": "抒情的",
//      "tagId": 1
//    }
    NSString *tempkeywordString;
    if(kStringIsEmpty(keywordString)){
        tempkeywordString = [NSString new];
    }
    else{
        tempkeywordString = keywordString;
    }
    NSDictionary *pramerDict = @{@"page":[NSString stringWithFormat:@"%ld",self.page]
                                 ,@"limit":@"100",
                                 @"keyword":tempkeywordString,
                                 @"tagId":[NSString stringWithFormat:@"%ld",tagId]};
        
        [[ZYFDataManager sharedInstance] POST:tempUrl dict:pramerDict succeed:^(id data) {
            
            NSLog(@"背景音乐数据List-pramerDict==%@--data==%@\n",pramerDict,data);
            
            NSDictionary *dictData = data;
            if([dictData isKindOfClass:[NSDictionary class]]){
                if([dictData[@"code"] isKindOfClass:[NSNumber class]]||[dictData[@"code"] isKindOfClass:[NSString class]]){
                    NSInteger codeInt = [dictData[@"code"] integerValue];
                    if(codeInt==200){
                        if([dictData[@"data"] isKindOfClass:[NSDictionary class]]){
                            NSDictionary *dictDataOut = dictData[@"data"] ;
                            if([dictDataOut[@"data"] isKindOfClass:[NSArray class]]){
                                NSArray *dataArr3  = dictDataOut[@"data"];
                                
                                if(dataArr3.count>0){
                                    for (int ii=0; ii<dataArr3.count; ii++) {
                                        NSDictionary *tempFinalDict = dataArr3[ii];
                                        xsBossIPBackgroundTableViewCellModel *md = [xsBossIPBackgroundTableViewCellModel yy_modelWithDictionary:tempFinalDict];
                                        if([tempFinalDict[@"id"] isKindOfClass:[NSNumber class]]||
                                           [tempFinalDict[@"id"] isKindOfClass:[NSString class]]){
                                           NSString *tempIdStr = [NSString stringWithFormat:@"%ld",[tempFinalDict[@"id"] integerValue]];
                                            md.Id = [tempIdStr integerValue];
                                        }
                                        [weakSelf.dataArray addObject:md];
                                    }
                                    
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        [weakSelf stopEndRefresh:weakSelf.dataArray];
                                    });
                                }
                                else{
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        [weakSelf stopEndRefresh:nil];
                                    });
                                }
                            }
                            else{
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    [weakSelf stopEndRefresh:nil];
                                });
                            }
                        }
                        else{
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [weakSelf stopEndRefresh:nil];
                            });
                        }
                    }
                    else{
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [weakSelf stopEndRefresh:nil];
                        });
                    }
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf stopEndRefresh:nil];
                    });
                }
            }
            else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf stopEndRefresh:nil];
                });
            }
            
        } failure:^(NSDictionary *error) {
            NSLog(@"getAudioDataWithAspectRatio--error.description==%@\n",error.description);
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf stopEndRefresh:nil];
            });
        }];
}


#pragma mark - stopEndRefresh
- (void)stopEndRefresh:(NSArray *) array {
    

    if (self.page  == 1) {
        if (self.mj_footer.isRefreshing) {
            [self.mj_footer endRefreshing];
        }
        [self.mj_header endRefreshing];
        [self.mj_footer resetNoMoreData];
    }else {
        if (array.count > 1) {
            [self.mj_footer endRefreshing];
        }else {
            [self.mj_footer endRefreshingWithNoMoreData];
        }
    }
    
    __weak typeof(self) weakself = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakself reloadData];
    });
}

@end





